//
//  TWRefreshHeader.swift
//  EyepetizerImitative
//
//  Created by 田伟 on 2017/4/12.
//  Copyright © 2017年 个人. All rights reserved.
//

import UIKit
import MJRefresh
import SnapKit

class TWRefreshHeader: MJRefreshHeader {

    fileprivate lazy var bigImageView : UIImageView = UIImageView()
    fileprivate lazy var smallImageView : UIImageView = UIImageView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        bigImageView.image = UIImage(named: "ICON_Loading_Out_42x28_")
        addSubview(bigImageView)
        bigImageView.snp.makeConstraints { (make) in
            make.center.equalTo(self)
        }
        
        smallImageView.image = UIImage(named: "ICON_Loading_In_42x28_")
        addSubview(smallImageView)
        smallImageView.snp.makeConstraints { (make) in
            make.center.equalTo(self)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    override var state: MJRefreshState{
        didSet {
            if self.state == MJRefreshState.idle {
                // 下拉可以刷新
                smallImageView.layer.removeAllAnimations()
            } else if self.state == MJRefreshState.pulling {
                // 松开立即刷新
                addRotationAnimation()
            } else if self.state == MJRefreshState.refreshing {
                // 正在刷新
                addRotationAnimation()
            }
        }
    }

    private func addRotationAnimation() {
        // 1创建动画
        let rotationAnim = CABasicAnimation(keyPath: "transform.rotation.z")
        // 2设置动画属性
        rotationAnim.fromValue = 0
        rotationAnim.toValue = (Double.pi) * 2
        rotationAnim.repeatCount = MAXFLOAT // 一直旋转
        rotationAnim.duration = 1
        rotationAnim.isRemovedOnCompletion = false
        // 3将动画添加到layer中
        smallImageView.layer.add(rotationAnim, forKey: nil)
    }
}
